/**
 * 
 */
package com.googlecode.xcarve.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author xinyun.du
 *
 * 2014年7月21日
 */
public class IntnetAddressUtils{
	
	private String hostAddress;
	private static IntnetAddressUtils instance = new IntnetAddressUtils();
	static final Logger logger = LoggerFactory.getLogger(IntnetAddressUtils.class);
	static final String localhost = "127.0.0.1";
	
	private IntnetAddressUtils(){
		try {
			this.hostAddress = InetAddress.getLocalHost().getHostAddress();
			if(StringUtils.equals(hostAddress, localhost)){
				this.hostAddress = getHostAddressByNetWork();
			}
		} catch (UnknownHostException e) {
			 logger.error("获取hostAddress 失败",e);
			 throw new IllegalStateException("获取 hostAddress 失败" , e);
		}
		
	}
	
	public static IntnetAddressUtils getInstance() {
		return instance;
	}
	 
	public String getHostAddress() {
		return hostAddress;
	}
	
	protected String getHostAddressByNetWork(){
		try {
			Enumeration<NetworkInterface> network = NetworkInterface.getNetworkInterfaces();
			while(network.hasMoreElements()){
				NetworkInterface net = network.nextElement();
				if(net.isLoopback() || net.isVirtual() || !net.isUp()){
					continue;
				} 
				Enumeration<InetAddress> addresses = net.getInetAddresses();
				while(addresses.hasMoreElements()){
					InetAddress address = addresses.nextElement();
					if(address.getHostAddress().startsWith("1") && !StringUtils.equals(address.getHostAddress(), localhost)){
						logger.info("..........this server hostAddress is {} .......",address.getHostAddress());
						return address.getHostAddress();
					}
				}
			}
		} catch (Exception e) {
			logger.error("获取serverIp 异常",e);
		}
		return null;
	}
	 
	 
}
